const https = require('https');
const http = require('http');
const { writeFile, readFile, fsExistsSync } = require('../../app/util');

const defaultGlobal = require('../default/global');
function compareObjects(obj1, obj2) {
  const diff = {};

  for (let key in obj1) {
    if (obj1.hasOwnProperty(key)) {
      if (typeof obj1[key] === 'object' && obj1[key] !== null && typeof obj2[key] === 'object' && obj2[key] !== null) {
        // 递归比较嵌套的对象
        const nestedDiff = compareObjects(obj1[key], obj2[key]);

        if (Object.keys(nestedDiff).length > 0) {
          diff[key] = nestedDiff;
        }
      } else if (obj1[key] !== obj2[key] && obj2[key]) {
        // 不同的值
        // diff[key] = {
        //     oldValue: obj1[key],
        //     newValue: obj2[key]
        // };
        diff[key] = obj2[key];
      }
    }
  }

  for (let key in obj2) {
    if (obj2.hasOwnProperty(key) && !obj1.hasOwnProperty(key)) {
      // obj2 有而 obj1 没有的属性
      diff[key] = obj2[key];
    }
  }

  return diff;
}

function isObjectEmpty(obj) {
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      return false; // 对象不为空
    }
  }
  return true; // 对象为空
}

function getTemplateName(template) {
  if (template === 'postdome') {
    return 'uspoststamp';
  }

  if (template === 'brooklyn') {
    return 'bklyn';
  }

  if (template === 'teye') {
    return 'ttdeye20';
  }

  if (template === 'trendyline') {
    return 'trendy_line';
  }

  if (fsExistsSync(`./src/theme/${template}`)) {
    return template;
  }

  if (fsExistsSync(`./src/theme/${template}20`)) {
    return template + '20';
  }
  console.log(template, '模版匹配失败');
  return '';
}
function setGlobalConfig(setting_data, template) {
  const defaultKeys = Object.keys(setting_data);
  const diff_global_item = {};

  defaultGlobal.forEach((item, index) => {
    item.settings.forEach((el, idx) => {
      if (el.id) {
        if (defaultKeys.includes(el.id)) {
          const differences = compareObjects(el, { default: setting_data[el.id] });
          if (!isObjectEmpty(differences)) {
            if (el.id === 'producr_image_fit') {
              diff_global_item[el.id] = {
                default: 'cover',
              };
            } else {
              diff_global_item[el.id] = differences;
            }
          }
        }
      }
    });
  });
  let defaultdiffglobal = {};
  template = getTemplateName(template);
  defaultdiffglobal = JSON.parse(readFile(`./src/theme/${template}/lib/config/diff_global.json`));
  Object.keys(diff_global_item).forEach((key) => {
    defaultdiffglobal.diffConfig[key] = diff_global_item[key];
    if (!defaultdiffglobal.diffConfig[key]) {
      console.log('没有匹配' + key);
    }
  });
  console.log('执行全局写入' + template);
  writeFile(`./src/theme/${template}/lib/config/diff_global.json`, JSON.stringify(defaultdiffglobal, '', '\t'));
}

function formatParams(params, type) {
  Object.keys(params).forEach((key) => {
    if (typeof params[key] === 'object' && params[key] !== null) {
      formatParams(params[key], 'object');
    }

    if (['id', 'alt', 'handle', 'title', 'url'].includes(key) && type == 'object') {
      params[key] = '';
    }
  });
}

// function getBlockSections(src){
//     const schema =  getBlockSchema(src);
// }

function getPageBlockConfig(sections, template) {
  const pageSections = [];
  template = getTemplateName(template);
  sections.forEach((item) => {
    item.params.blocks.forEach((el) => {
      formatParams(el);
    });
    formatParams(item.params.settings);

    if (['header', 'footer'].includes(item.type)) {
      const liquidPath = `./src/theme/${template}/sections/${item.type}.liquid`;
      const content = readFile(liquidPath);
      let schema = {};
      const schemaRegExpStr = /{% schema %}([\s\S]*?){% endschema %}/g;
      const schemBody = content.match(schemaRegExpStr);
      if (schemBody) {
        schema = JSON.parse(schemBody[0].replace(/({% schema %})|({% endschema %})/g, ''));
      }

      if (item.type === 'footer' && item.params.settings['copyright']) {
        item.params.settings['copyright'] = '©{{ date_year }} {{ storeConfig.name }} {{ current_domain }}';
      }
      schema.default = item.params;
      writeFile(liquidPath, content.replace(schemaRegExpStr, `{% schema %}\n${JSON.stringify(schema, '', '\t')}\n{% endschema %}`));
      return;
    }
    pageSections.push({
      type: item.type,
      fixed: '',
      params: item.params,
    });
  });
  console.log('执行页面写入' + template);
  writeFile(`./src/theme/${template}/lib/config/index_index.json`, JSON.stringify(pageSections, '', '\t'));
}
function getTemplateConfigs(hostname, token, id,callback) {
  var options = {
    hostname: hostname,
    port: 443,
    path: `/api/themes/${id}/data?route=index%2Findex&route_handle=`,
    method: 'GET',
    headers: {
      token: token,
    },
  };

  var mData = '';
  var req = https.request(options, function (res) {
    res.setEncoding('utf-8');
    res.on('data', function (d) {
      mData += d;
    });
    res.on('end', function () {
      var data = JSON.parse(mData);
      if (!data.code) {
        getPageBlockConfig(data.data.sections, hostname.split('.')[0]);
        setGlobalConfig(data.data.global, hostname.split('.')[0]);
        callback && callback();
      } else {
        console.log('getTemplateConfigs 错误', data.msg);
      }
    });
  });
  req.on('error', function (e) {
    console.error('getTemplateConfigs ==========================' + hostname + e);
  });
  req.end();
}

function getTemplateGlobalConfig(hostname, token, id) {
  var options = {
    hostname: hostname,
    port: 443,
    path: `/api/themes/${id}/configs`,
    method: 'GET',
    headers: {
      token: token,
    },
  };

  var mData = '';
  var req = https.request(options, function (res) {
    res.setEncoding('utf-8');
    res.on('data', function (d) {
      mData += d;
    });
    res.on('end', function () {
      var data = JSON.parse(mData);
      if (!data.code) {
        setGlobalConfig(data.data.setting_data.global, hostname.split('.')[0]);
      } else {
        console.log('getTemplateConfigs 错误', data.msg);
      }
    });
  });
  req.on('error', function (e) {
    console.error('getTemplateConfigs==========================' + hostname + e);
  });
  req.end();
}

function getTemplateDefault(hostname, token,callback) {
  var options = {
    hostname: hostname,
    port: 443,
    path: `/api/themes/default`,
    method: 'GET',
    headers: {
      token: token,
    },
  };

  var mData = '';
  var req = https.request(options, function (res) {
    res.setEncoding('utf-8');
    res.on('data', function (d) {
      mData += d;
    });
    res.on('end', function () {
      var data = JSON.parse(mData);
      if (!data.code) {
        // getTemplateGlobalConfig(hostname, token, data.data.id);
        getTemplateConfigs(hostname, token, data.data.id,callback);
      } else {
        console.log('getTemplateDefault 错误', data.msg);
      }
    });
  });
  req.on('error', function (e) {
    console.error('getTemplateDefault================================' + hostname + e);
  });
  req.end();
}

function  getStoresToken(id,callback) {
  var options = {
    hostname: 'account-test.oemsaas.cn',
    port: 80,
    path: `/account-api/front/stores/token/${id}`,
    method: 'GET',
    headers: {
      'front-token': '8c7ed642-1416-464a-a66f-ac0c8bff7ad8',
    },
  };
  var mData = '';
  var req = http.request(options, function (res) {
    res.setEncoding('utf-8');
    res.on('data', function (d) {
      mData += d;
    });
    res.on('end', function () {
      try {
        var data = JSON.parse(mData);
        if (!data.code) {
          getTemplateDefault(data.data.shop_domain, data.data.token,callback);
        } else {
          console.log('getStoresToken 错误', data.msg);
        }
      } catch (error) {
        console.log(error);
      }
    });
  });
  req.on('error', function (e) {
    console.error('getStoresToken=====================' + e);
  });
  req.end();
}

const store = {
  ambianimaless20: 43544,
  athens: 37784,
  avatar: 51909,
  bklyn: 25213,
  california: 34394,
  ceborn20: 51976,
  chic: 51979,
  critical: 28160,
  district20: 45180,
  envy: 26030,
  expanse: 33552,
  fashionopolism: 25843,
  fetch20: 51862,
  flash20: 43243,
  focal: 33963,
  Geek20: 41906,
  goya: 25732,
  goyaFashion: 25654,
  hero: 25896,
  hibaes: 25593,
  hyde: 25572,
  default: 25214,
  impress: 39928,
  kingdom20: 49680,
  Stockholm: 28843,
  avatar20: 51909,
  light: 37567,
  maranello20: 51791,
  mavon20: 47962,
  mode20: 51886,
  nova: 25240,
  oliviamark20: 51978,
  puaintapets: 36972,
  punk: 25139,
  quest: 28158,
  rauhg: 33119,
  razzi: 25536,
  rcdoo20: 44705,
  refresh: 30987,
  ride: 29616,
  sound20: 51842,
  spark: 34639,
  sport: 28161,
  testament: 25411,
  ttdeye20: 46343,
  uspoststamp: 36518,
  vantage: 33310,
  warehouse20: 51877,
  wind20: 38778,
  zest20: 38144,
  shoes20: 52034,
  ueeshop20: 52038,
  maklia20: 52053,
  jewelry: 95925,
  apparel: 96001,
  appliances: 96002,
  ornaments: 96003,
  metal: 96007,
  socks: 95977,
  trendy_line: 96009,
  area20: 95902,
  tropicalpink: 96016,
  neonglow: 96015,
  korea:96017,
  random: 96020,
  astro: 96021,
};

module.exports = {
  getTemplateConfigs,
  getTemplateGlobalConfig,
  getTemplateDefault,
  getStoresToken,
  syncTemplates: function (templates,callback) {
    getStoresToken(store[templates],callback);
  },
};
